/*
 * @Author: zxhuan
 * @Date: 2019-05-14 21:40:59
 * @blog: http//:www.zxhuan.com
 * @Last Modified time: 2019-05-14 21:40:59
 */
import CryptoJS from 'crypto-js'
import crypto from 'crypto'

// 秘钥设置
const Key = 'cp1t@dsy'
// 加密原生
export const encryptByDES = (message, key = Key) => {
    var keyHex = CryptoJS.enc.Utf8.parse(key)
    var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    })
    return encrypted.toString()
}
//解密原生
export const decryptByDES = (ciphertext, key = Key) => {
    var keyHex = CryptoJS.enc.Utf8.parse(key)
    var decrypted = CryptoJS.DES.decrypt({
        ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
    }, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        })
    return decrypted.toString(CryptoJS.enc.Utf8)
}

// 加密改（obj） =》 des字符串
export const dataEncoder = (obj, key = Key) => {
    // 如果有中文，则需要encodeURIComponent转义再des加密，没有则不需要
    // 如果是对象则处理加密，否则不加密
    if(Object.prototype.toString.call(obj) === '[object Object]'){
        if(obj.hasOwnProperty('PassWord')
            ||obj.hasOwnProperty('NewPassWord')
            ||obj.hasOwnProperty('Password')){
            return encryptByDES(JSON.stringify(obj), key)

        }
        else{
            return encryptByDES(encodeURIComponent(JSON.stringify(obj)), key)
        }
    }else if(obj instanceof Array){
        console.log('arr')
        return encryptByDES(encodeURIComponent(JSON.stringify(obj)), key)
    }


}
//  解密改（des字符串） =》  obj
export const dataDecoder = (ciphertext, key = Key) => {
    return JSON.parse(decodeURIComponent(decryptByDES(ciphertext, key)))
}

export const formatNumber = (n) => {
    const str = n.toString()
    return str[1] ? str : `0${str}`
}

export const formatTime = (date) => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()

    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    const t1 = [year, month, day].map(formatNumber).join('/')
    const t2 = [hour, minute, second].map(formatNumber).join(':')

    return `${t1} ${t2}`
}

export const md5Encoder = (string) => {
    return crypto.createHash('md5').update(string).digest('hex').toUpperCase()
}
